package com.it.sun.easychat.framework.security;

import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSON;
import com.it.sun.easychat.framework.security.environment.EnvProperties;
import com.it.sun.easychat.framework.security.filter.PerOperationFilter;
import com.it.sun.easychat.framework.security.handler.LoginSuccessHandler;
import com.it.sun.easychat.model.util.ResultHelper;
import com.it.sun.easychat.model.vo.ResultVO;
import com.it.sun.esaychat.user.service.IUserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.xml.ws.RequestWrapper;
import java.nio.charset.Charset;

/**
 * @author sunmannian
 * @ClassName WebSecurityConfiguration
 * @Date 2020/5/23 21:38
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/23
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private IUserServices userServices;

    @Autowired
    private EnvProperties envProperties;

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(envProperties.getIgnoreUrls().toArray(new String[0])).permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .cors()
                .and()
                .addFilterAfter(new PerOperationFilter(), CorsFilter.class)
                .apply(new JsonLoginConfigurer<>())
                .loginSuccessHandler(loginSuccessHandler)
                .and()
                .logout()
                .logoutUrl(envProperties.getLogoutUrl())
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userServices);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(PasswordEncoderFactories.
                createDelegatingPasswordEncoder());
        auth.authenticationProvider(daoAuthenticationProvider);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    private AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            response.setContentType(ContentType.JSON.getValue());
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCharacterEncoding(Charset.defaultCharset().name());
            ResultVO<Void> resultVO = ResultHelper.getFailed(
                    HttpStatus.UNAUTHORIZED.value(),
                    HttpStatus.UNAUTHORIZED.getReasonPhrase(), null);
            response.getWriter().write(JSON.toJSONString(resultVO));
        };
    }

    @Bean()
    @ConfigurationProperties(prefix = "security")
    public EnvProperties envProperties() {
        return new EnvProperties();
    }
}
